package edu.ynu.se.xiecheng.achitectureclass.project.service;

import edu.ynu.se.xiecheng.achitectureclass.project.dao.DataDAO;
import edu.ynu.se.xiecheng.achitectureclass.project.po.entity.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class SoilDataService {

    @Autowired
    private DataDAO dataDAO;

    @Autowired
    private SoilTokenService soilTokenService;

    @Autowired
    private RestTemplate restTemplate;

    // 获取土壤数据的 URL
    private static final String SOIL_DATA_URL = "https://fbox360.com/api/v2/dmon/value/get?boxNo=300822040454";

    // 土壤检测设备的传感器 ID 列表
    private static final List<String> SENSOR_IDS = Arrays.asList(
            "327061586065758005",
            "327061586065758015",
            "327061586065758006",
            "327061586065758007",
            "327061586065758008",
            "327061586065758009",
            "327061586065758010",
            "327061586065758013",
            "327061586065758014",
            "327061586065758012",
            "327061586065758011"
    );

    /**
     * 获取并存储土壤数据
     *
     * @return 存储的土壤数据列表
     */
    public List<Data> fetchAndSaveSoilData() {
        // 获取有效的 token
        String accessToken = soilTokenService.getOrRefreshSoilToken();
        if (accessToken == null) {
            throw new RuntimeException("Failed to get access token");
        }

        // 获取土壤数据
        List<Map<String, Object>> soilDataList = fetchSoilData(accessToken);
        if (soilDataList == null || soilDataList.isEmpty()) {
            throw new RuntimeException("Failed to fetch soil data: API returned empty data");
        }

        // 存储土壤数据
        List<Data> savedDataList = new ArrayList<>();
        for (Map<String, Object> soilData : soilDataList) {
            Data data = new Data();
            data.setSerialId((String) soilData.get("id"));
            data.setBoxNo((String) soilData.get("boxId"));
            data.setName((String) soilData.get("name"));
            data.setValue(((Number) soilData.get("value")).doubleValue());
            data.setTimestamp(LocalDateTime.now());
            data.setIsDeleted(false);

            savedDataList.add(dataDAO.save(data));
        }

        return savedDataList;
    }

    /**
     * 获取土壤数据
     *
     * @param accessToken 访问 token
     * @return 土壤数据列表
     */
    private List<Map<String, Object>> fetchSoilData(String accessToken) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + accessToken);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("ids", SENSOR_IDS);

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        ResponseEntity<List> response = restTemplate.postForEntity(SOIL_DATA_URL, requestEntity, List.class);

        if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
            return (List<Map<String, Object>>) response.getBody();
        }

        throw new RuntimeException("Failed to fetch soil data: " + response.getStatusCode());
    }
}